package com.example.newbiechen.ireader.service.boluoxs;

import android.util.Log;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by robrk on 2019/3/10.
 */

public class ArticleService {
    private StringBuffer content;
    private String url;
    private String title;
    private boolean isFinish;
    private ArticleDownloadFinish articleDownloadFinish;

    public boolean isFinish() {
        return isFinish;
    }

//    public void setFinish(boolean finish) {
//        isFinish = finish;
//    }

    public StringBuffer getContent() {
        return content;
    }

    public String getTitle() {
        return title;
    }

    public ArticleService(String url, String title) {
        this.content = new StringBuffer();
        this.url = url;
        this.title = title;
        this.isFinish = false;
    }

    public void download(ArticleDownloadFinish articleDownloadFinish){
        this.articleDownloadFinish = articleDownloadFinish;
        this.isFinish = false;
        this.getPageByUrl(this.url);
    }

//    public void getArticleText(String html){
//        // <article id="nr"></article>
////                Pattern pattern = Pattern.compile("<article id=\"nr\"></article>");
//
//        List<String> lst = HtmlHelper.getTagText(html, "<article id=\"nr\">", "</article>");
//        for (String str : lst) {
//            str = str.replace(" ", "");
//            str = str.replace("&nbsp;", " ").replace("<br>", "\n");
//            System.out.println(str);
//
//
//        }
//    }

    public void getNextPage(String html){
        // <a class="dise" href="/0/188/126575_2.html">下一章</a>
        Pattern aPattern = Pattern.compile("<a class=\"dise\" href=\"([^\"]*?)\">下一章</a>");
        Matcher m = aPattern.matcher(html);
        while (m.find()){
            System.out.println(m.group());
            String url = m.group(1);
            System.out.println("url:" + url);
            this.getPageByUrl(url);
        }
    }

    private void getPageByUrl(String urlPath){
        String url = "https://m.boluoxs.com" + urlPath;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new ArticleCallBack(this));
    }

    public void save(){
        this.isFinish = true;
        System.out.println("\n\nsave file:" + this.getTitle());
        System.out.println("\n\n" + this.getContent().toString());
        if(this.articleDownloadFinish != null){
            this.articleDownloadFinish.onFinish(this.getTitle(), this.getContent().toString());
        }
    }
}
